package com.wangyadong.hobby.metric.timer;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import static org.apache.tomcat.jni.Thread.current;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/12/1910:44
 **/
public class TimerExample {
    private static MetricRegistry registry = new MetricRegistry();
    /***block queue**/
    private static final BlockingDeque queue = new LinkedBlockingDeque(1_000);


    private static ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    private static final Timer timer = registry.timer("request", Timer::new);

    public static void main(String[] args) {
        reporter.start(10, TimeUnit.SECONDS);
        while (true) {
            business();
        }
    }

    private static void business() {
        Timer.Context context = timer.time();
        try {
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(12));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            long stop = context.stop();
            System.out.println("============" + stop);
        }
    }
}
